package com.yt.sys.api.client;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.yt.common.constant.Result;
import com.yt.common.enums.CodeEnum;
import com.yt.common.utils.StrUtils;
import com.yt.db.utils.RedisTokenUtil;
import com.yt.sys.models.bo.LoginInfoSaveBO;
import com.yt.sys.models.service.ILoginInfoService;
import com.yt.sys.models.vo.LoginInfoVO;
import com.yt.sys.models.vo.SysUserVO;
import com.yt.sys.service.SysUserServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

/**
 * @author
 * @dese
 * @date 2025/10/23 13:56
 */
@RestController
@RequestMapping("/api/loginInfo")
@Slf4j
@Api(value = "LoginInfoApiController", tags = "用户登录信息Api接口")
public class LoginInfoApiController {

    @DubboReference
    private ILoginInfoService loginInfoService;
    @Autowired
    private RedisTokenUtil redisTokenUtil;
    @Autowired
    private DefaultKaptcha captchaProducer;
    @Resource
    private SysUserServiceImpl sysUserService;
    @ApiOperation(value = "登录", notes = "登录")
    @PostMapping(value = "/login")
    public Result<HashMap<String, Object>> login(@RequestBody LoginInfoSaveBO saveBO) {
        HashMap<String, Object> map = new HashMap<String, Object>();
        if (saveBO == null) {
            return new Result<>(CodeEnum.FAIL_100002);
        }
        // 验证码验证
        String captchaKey = saveBO.getCaptchaKey();
        String captchaCode = saveBO.getCaptchaCode();

        if (StrUtils.isEmpty(captchaKey) || StrUtils.isEmpty(captchaCode)) {
            return new Result<>(CodeEnum.FAIL_Login_1010);
        }

        String storedCaptcha = redisTokenUtil.getCaptcha(captchaKey);
        if (storedCaptcha == null) {
            return new Result<>(CodeEnum.FAIL_Login_1011);
        }

        if (!storedCaptcha.equalsIgnoreCase(captchaCode)) {
            return new Result<>(CodeEnum.FAIL_Login_1012);
        }
        //用户判断账号是否存在，
        LoginInfoVO userLoginVO = loginInfoService.getLogin(saveBO);
        if (userLoginVO == null) {
            return new Result<>(CodeEnum.FAIL_USER_200003);
        }
        //如果存在就判断他密码是否正确
        SysUserVO sysUserVO = loginInfoService.getSysLogin(saveBO);
        if (sysUserVO == null) {
            return new Result<>(CodeEnum.FAIL_USER_200006);
        }

        //生成Token并存入到Redis
        String token = redisTokenUtil.generateToken(sysUserVO.getUserName());
        sysUserVO.setToken(token);


        map.put("sysUserVO", sysUserVO);
        return new Result<>(map);

    }


    @ApiOperation(value = "获取验证码", notes = "获取登录验证码")
    @GetMapping("/getCaptcha")
    public Result<HashMap<String, String>> getCaptcha() {
        HashMap<String, String> result = new HashMap<>();
        // 生成验证码文本
        String captchaText = captchaProducer.createText();
        // 生成验证码图片
        BufferedImage image = captchaProducer.createImage(captchaText);

        // 生成唯一标识
        String captchaKey = UUID.randomUUID().toString();
        // 存储验证码到Redis，设置5分钟过期
        redisTokenUtil.setCaptcha(captchaKey, captchaText, 300);

        // 转换图片为Base64
        try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
            ImageIO.write(image, "jpg", baos);
            String base64Image = "data:image/jpeg;base64," + Base64.getEncoder().encodeToString(baos.toByteArray());
            result.put("captchaKey", captchaKey);
            result.put("captchaImage", base64Image);
            return new Result<>(result);
        } catch (IOException e) {
            log.error("生成验证码失败", e);
            return new Result<>(CodeEnum.FAIL_Login_1013);
        }
    }
}

